import yaml
import logging
import os
from logging.handlers import TimedRotatingFileHandler
from playhouse.pool import PooledMySQLDatabase
from playhouse.shortcuts import ReconnectMixin

# 读取YAML配置文件
with open('config.yaml', 'r') as file:
    config = yaml.safe_load(file)

project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 构建日志文件的完整路径
log_file_path = os.path.join(project_root, 'crypto_cycle.log')
# 创建一个日志器
logger = logging.getLogger()
logger.setLevel(logging.INFO)

# 创建 TimedRotatingFileHandler
handler = TimedRotatingFileHandler(
    log_file_path,
    when="midnight",
    interval=1,
    backupCount=5
)
handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))

# 将处理程序添加到日志器
# logger.addHandler(handler)  # 如果需要输出到屏幕就把这行代码注释掉


# 实现这个类可以避免崩溃
class ReconnectMySQLDatabase(ReconnectMixin, PooledMySQLDatabase):
    pass


def get_db():
    base_config = config['database']
    db = ReconnectMySQLDatabase(base_config['db'], host=base_config['host'], port=3306,
                                user=base_config['user'], password=base_config['password'])
    return db


# 确保数据库连接关闭的装饰器
def close_db(fn):
    def inner(*args, **kwargs):
        db = get_db()
        try:
            return fn(*args, **kwargs)
        finally:
            if not db.is_closed():
                db.close()

    return inner
